package com.cskaoyan.rocketmq.transaction;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 创建日期: 2023/01/18 15:17
 *
 * @author ciggar
 *
 * 事务消息的消费者
 */
public class TransactionConsumer {

    public static void main(String[] args) throws MQClientException {

        // 1. 构建一个消息的消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("transaction_consumer_group");


        // 2. 设置注册中心
        consumer.setNamesrvAddr("localhost:9876");

        // 3. 设置消息监听器
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                System.out.println("consumeMessage： 收到了消息");

                MessageExt messageExt = msgs.get(0);

                // 获取消息的内容
                byte[] body = messageExt.getBody();
                String content = new String(body, Charset.forName("utf-8"));

                System.out.println("content: "  + content);

                // 返回消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 4. 订阅主题
        consumer.subscribe("transaction_test_topic","*");


        // 5. 启动
        consumer.start();
    }
}
